package com.xdf.swids.datasource;
import com.xdf.swids.model.TenantInfo;
import com.xdf.swids.service.ITenantInfoService;
//import com.mybatis.plus.util.SpringContextUtils;
import com.xdf.swids.utils.SpringContextUtils;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 动态数据源
 *
 * @author wulongbo
 * @version 1.0
 * @Description 动态数据源初始化
 * @date 2020/12/5 11:11
 */
@Slf4j
@Configuration
public class DynamicDataSourceInit {
    @Autowired
    private ITenantInfoService tenantInfoService;
    @Bean
    public void initDataSource() {
        log.info("======初始化动态数据源=====");
        DynamicDataSource dynamicDataSource = (DynamicDataSource) SpringContextUtils.getBean("dynamicDataSource");
        log.info("dynamicDataSource:" + dynamicDataSource.toString());
        HikariDataSource master = (HikariDataSource) SpringContextUtils.getBean("master");
        log.info("master数据源：" + master.toString());

        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("master", master);
        List<TenantInfo> tenantList = tenantInfoService.selectAll();
        for (TenantInfo tenantInfo : tenantList) {
            log.info(tenantInfo.toString());
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setDriverClassName(tenantInfo.getDatasource_driver());
            dataSource.setJdbcUrl(tenantInfo.getDatasource_url());
            dataSource.setUsername(tenantInfo.getDatasource_username());
            dataSource.setPassword(tenantInfo.getDatasource_password());
            dataSource.setDataSourceProperties(master.getDataSourceProperties());
            dataSourceMap.put(tenantInfo.getTenant_id(), dataSource);
        }
        // 设置数据源
        dynamicDataSource.setDataSources(dataSourceMap);
        /**
         * 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
         */
        dynamicDataSource.afterPropertiesSet();
    }
}